package com.richman.ps38;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import com.richman.controller.DaShui;
import com.richman.ps38.entity.Event;
import com.richman.utils.Common;
 
public class PS38Selenium {

	
	
	CloseableHttpClient httpClient = null;
	RequestConfig requestConfig = null;
	HttpClientContext clientContext = null;
	

	
	int defaultTimeout = 15*1000;
	
	 {
		 
		
		 
	    requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
	    requestConfig = RequestConfig.copy(requestConfig).setRedirectsEnabled(false).build();//禁止重定向 ， 以便获取cookieb18
	    requestConfig = RequestConfig.copy(requestConfig).setConnectTimeout(defaultTimeout).setConnectionRequestTimeout(defaultTimeout).setSocketTimeout(defaultTimeout).build();//设置超时
	    httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
	 }
	
	
	String withoutMemberServiceCookie = "";
	
	String withMenberService = "";
	
	Map<String, String> myCookies = new HashMap<String, String>();
	
	String ADDRESS = "https://www.ps3838.com/";
	
	String ACCOUNT = "004Z000006";
	String PWD = "aaaa2345";
	
	
	int grabEventsfailtimes = 0;
	
	long loginTime = 0L;
	
    //-1 最初状态  ,  1登录成功  2抓取成功
    int statusCode = -1;
	
    public  void setLoginParams(String address, String account, String pwd){
		
			ADDRESS = address;
			ACCOUNT = account;
			PWD = pwd;
	}
    
    public int getStatusCode() {

   	 return statusCode;
    }
    
    
    public void updateStatusCode(int i) {

   	 if(i!= 3) {
   		System.out.println(ACCOUNT + ": update ps38_statusCode from " +   Integer.toString(statusCode) + " to " + Integer.toString(i));
   	 }
   	 
   	 if(i == -3) {
   		grabEventsfailtimes++;
   	 }
   	 
   	 if(i ==3) {
   		grabEventsfailtimes = 0;
   	 }
   	 
   	 if(grabEventsfailtimes > 10) {
   		 
   		grabEventsfailtimes = 0;
   		 
   		 System.out.println("grab failed times big than 10 need relogin");
   		 
   		 i = -1;
   	 }
   	 
   	 statusCode = i;
    }
    
    
    public String getAccount() {
    	return ACCOUNT;
    }
    
    
	
    public static void main(String[] args) throws Exception {


    	System.setProperty("webdriver.chrome.driver","C:\\chromedriver_win32\\chromedriver.exe");

        PS38Selenium ts = new PS38Selenium();

        String res = "";
        
        
        boolean blogTofile = true;
        
    	PrintStream psFile = null;
    	PrintStream psConsole = null;
        
        
        
		if(blogTofile == true) {
			try {
				// 生成路径
				File dir = new File("log");
				if (dir.exists()) {
				} else {
					dir.mkdirs();
				}

				// 把输出重定向到文件
				
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");// 设置日期格式
				
				psFile = new PrintStream("log/" + df.format(new Date())
							+ ".txt");
				
				
				psConsole = System.out;

				System.setOut(psFile);
				System.setErr(psFile);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
        
        
        int failedTimes = 1;
        
        
        while(true) {
        	
        	
            if(ts.Login() == 1) {
            	
            	Thread.sleep(20000);
            	
            	res = ts.getMatches();

            	
            	if(res.toLowerCase().contains("robot")) {
            		
            		System.out.println("first grab fuck robot");
            		
            		Thread.sleep(failedTimes * 30*1000);
            		
            		failedTimes++;
            		
            		continue;
            	}
            	
            	Thread.sleep(3000);
            	
            	res = ts.getBalance();
            	System.out.println("balance:" + res);
            	
            	failedTimes = 1;

            }else {
            	
            	 Thread.sleep(10000);
            	
            	continue;
            }
            

            Thread.sleep(2000);

            
            int robottimes = 0;
            
            for(int i = 0; i < 5000000; i++) {
            	
            	if(i%2 == 0) {
            		res = ts.getMatches();
            	}else {
            		res = ts.getMatches();
            	}
            	
            	
            	
            	
            	
            	if(res.toLowerCase().contains("robot")) {
            		System.out.println("Fuck robot");
            		
            		robottimes++;
            		
            		if(robottimes >= 2) {
            			
            			System.out.println(i);
            			
            			break;
            		}
            		
            		
            	}
            	
            	System.out.println(res.substring(0, 100));
            	
            	Thread.sleep(6000);
            	
            }
            
            Thread.sleep(190000);
        	
        }
        

        
        
    }
    
    
    public String getDanshi() {
        try {

        	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        	
        	long currentTimeMillis = System.currentTimeMillis();
        	
        	//http://www.ps3838.com/sports-service/sv/odds/events?mk=1&sp=29&ot=4&btg=1&o=1&lg=&ev=&d=2019-01-30&l=3&v=1548826606457&more=false&c=CN&tm=0&g=QQ%3D%3D&pa=0&_=1548815879288&locale=zh_CN
        	
        	String uri = ADDRESS + "sports-service/sv/odds/events?mk=1&sp=29&ot=4&btg=1&o=1&lg=&ev=&d=" + df.format(currentTimeMillis + 12*60*60*1000) + "&l=3&v="+ currentTimeMillis +"&me=0&more=false&c=CN&tm=0&g=QQ%3D%3D&pa=0&_=" + loginTime + "&locale=zh_CN";
        	
            HttpGet httpget = new HttpGet(uri);
            

            String getcookies = getmyCookie(false);
            
            if(!getcookies.equals("")) {
            	httpget.addHeader("Cookie", getcookies);
            }
            
            httpget.addHeader("Accept","application/json, text/javascript, */*; q=0.01");
            
            httpget.addHeader("Accept-Encoding","");
            httpget.addHeader("Accept-Language","zh-CN,zh;q=0.9");
            httpget.addHeader("Connection","keep-alive");
            httpget.addHeader("Host","www.ps3838.com");

            httpget.addHeader("Referer",ADDRESS + "zh-cn/sports");
            
            if(!ADDRESS.contains("https")) {
            	httpget.addHeader("Upgrade-Insecure-Requests", "1");
            }
            

            httpget.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
            httpget.addHeader("X-Requested-With", "XMLHttpRequest");


            
            RequestConfig localRequestConfig = RequestConfig.copy(requestConfig).setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout).build();
            httpget.setConfig(localRequestConfig);

            CloseableHttpResponse response = httpClient.execute(httpget); 
            

            
            
            
            try{
            	
            	
            	
            	if(response.getStatusLine().toString().indexOf("302 Found") > 0) {
             	   return response.getFirstHeader("Location").getValue();
                }
                HttpEntity entity = response.getEntity(); 
                
                String res = EntityUtils.toString(entity, "UTF-8");
                
                if(res != null && res.length() > 0 ){     
                	//System.out.println(res);
                	
                	if(res.toLowerCase().contains("robot")) {
                		System.out.println(res);
                		updateStatusCode(-1);
                	}
                	
                    return res;
                }
            }finally{
                httpget.releaseConnection();
                response.close();
            }
            

            

        }catch (Exception e){
        	e.printStackTrace();
        }
        
        return null;
    }
    
    
    public String getGunqiu() {
        try {

        	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        	
        	long currentTimeMillis = System.currentTimeMillis();
        	
        	//http://www.ps3838.com/sports-service/sv/odds/events?mk=2&sp=29&ot=1&btg=1&o=1&lg=&ev=&d=2019-01-30&l=3&v=1548823963492&more=false&c=CN&tm=0&g=QQ%3D%3D&pa=0&_=1548815879209&locale=zh_CN
        	
        	String uri = ADDRESS + "sports-service/sv/odds/events?mk=2&sp=29&ot=4&btg=1&o=1&lg=&ev=&d=" + df.format(currentTimeMillis + 12*60*60*1000) + "&l=3&v="+  currentTimeMillis+ "&more=false&c=CN&tm=0&g=QQ%3D%3D&pa=0&_=" + loginTime + "&locale=zh_CN";
        	
            HttpGet httpget = new HttpGet(uri);
            

            String getcookies = getmyCookie(false);
            
            if(!getcookies.equals("")) {
            	httpget.addHeader("Cookie", getcookies);
            }
            
            httpget.addHeader("Accept","application/json, text/javascript, */*; q=0.01");
            
            httpget.addHeader("Accept-Encoding","");
            httpget.addHeader("Accept-Language","zh-CN,zh;q=0.9");
            httpget.addHeader("Connection","keep-alive");
            httpget.addHeader("Host","www.ps3838.com");

            httpget.addHeader("Referer",ADDRESS + "zh-cn/sports");
            
            if(!ADDRESS.contains("https")) {
            	httpget.addHeader("Upgrade-Insecure-Requests", "1");
            }

            httpget.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
            httpget.addHeader("X-Requested-With", "XMLHttpRequest");

            
            RequestConfig localRequestConfig = RequestConfig.copy(requestConfig).setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout).build();
            httpget.setConfig(localRequestConfig);

            CloseableHttpResponse response = httpClient.execute(httpget); 
            

            
            
            
            try{
            	if(response.getStatusLine().toString().indexOf("302 Found") > 0) {
             	   return response.getFirstHeader("Location").getValue();
                }
                HttpEntity entity = response.getEntity(); 
                
                String res = EntityUtils.toString(entity, "UTF-8");
                
                if(res != null && res.length() > 0 ){
                	
                	if(res.toLowerCase().contains("robot")) {
                		updateStatusCode(-1);
                	}
                	
                    return res;
                }
            }finally{
                httpget.releaseConnection();
                response.close();
            }
            

            

        }catch (Exception e){
        	e.printStackTrace();
        }
        
        return null;
    }
    
    
    public String getMatches() {
        try {

        	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        	
        	long currentTimeMillis = System.currentTimeMillis();
        	
        	//mk=2 滚球
        	String uri = ADDRESS + "sports-service/sv/odds/events?mk=2&sp=29&ot=4&btg=1&o=1&lg=&ev=&d=" + df.format(currentTimeMillis+12*60*60*1000) + "&l=3&v=0&me=0&more=false&c=CN&tm=0&g=&pa=0&_=" + currentTimeMillis + "&locale=zh_CN";
        	
            HttpGet httpget = new HttpGet(uri);
            
            String getcookies = getmyCookie(false);
            
            if(!getcookies.equals("")) {
            	httpget.addHeader("Cookie", getcookies);            	
//            	System.out.println("url:" + uri);
//            	System.out.println("cookie:" + getcookies);            	
            }
            
            
            
            httpget.addHeader("Accept","application/json, text/javascript, */*; q=0.01");
            
            httpget.addHeader("Accept-Encoding","");
            httpget.addHeader("Accept-Language","en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7");
            httpget.addHeader("Connection","keep-alive");
            httpget.addHeader("Host","www.ps3838.com");

            httpget.addHeader("Referer",ADDRESS + "zh-cn/sports");
            
            if(!ADDRESS.contains("https")) {
            	httpget.addHeader("Upgrade-Insecure-Requests", "1");
            }

            httpget.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
            httpget.addHeader("X-Requested-With", "XMLHttpRequest");

            
            RequestConfig localRequestConfig = RequestConfig.copy(requestConfig).setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout).build();
            httpget.setConfig(localRequestConfig);

            CloseableHttpResponse response = httpClient.execute(httpget); 
            

            setCookie(response);
            
            
            try{
            	
            	
            	
            	if(response.getStatusLine().toString().indexOf("302 Found") > 0) {
             	   return response.getFirstHeader("Location").getValue();
                }
                HttpEntity entity = response.getEntity(); 
                
                String res = EntityUtils.toString(entity, "UTF-8");
                
                if(res != null && res.length() > 0 ){     
                	//System.out.println(res);
                	
                	if(res.toLowerCase().contains("robot")) {
                		System.out.println(res);
                		updateStatusCode(-1);
                		return "";
                	}
                	
                	
                    if(!res.contains("{")) {
                    	
                    	System.out.println("grab matches without { failed");
                    	
                    	updateStatusCode(-3);
                    	
                    	return "";
                    }
                    
                    //System.out.println(res);
                    
                    parseMatches(res);
                	
                    return res;
                }
            }finally{
                httpget.releaseConnection();
                response.close();
            }
            

            

        }catch (Exception e){
        	e.printStackTrace();
        }
        
        return null;

    }
    

    
    
    public String getDanshiMatches() {
        try {

        	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        	
        	long currentTimeMillis = System.currentTimeMillis();
        	
        	
        	//单式加滚球都有
        	String uri = ADDRESS + "sports-service/sv/odds/events?mk=1&sp=29&ot=4&btg=1&o=1&lg=&ev=&d=" + df.format(currentTimeMillis+12*60*60*1000) + "&l=3&v=0&me=0&more=false&c=CN&tm=0&g=&pa=0&_=" + currentTimeMillis + "&locale=zh_CN";
        	
            HttpGet httpget = new HttpGet(uri);
            

            String getcookies = getmyCookie(false);
            
            if(!getcookies.equals("")) {
            	httpget.addHeader("Cookie", getcookies);            	
//            	System.out.println("url:" + uri);
//            	System.out.println("cookie:" + getcookies);            	
            }
            
            
            
            httpget.addHeader("Accept","application/json, text/javascript, */*; q=0.01");
            
            httpget.addHeader("Accept-Encoding","");
            httpget.addHeader("Accept-Language","en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7");
            httpget.addHeader("Connection","keep-alive");
            httpget.addHeader("Host","www.ps3838.com");

            httpget.addHeader("Referer",ADDRESS + "zh-cn/sports");
            
            if(!ADDRESS.contains("https")) {
            	httpget.addHeader("Upgrade-Insecure-Requests", "1");
            }

            httpget.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
            httpget.addHeader("X-Requested-With", "XMLHttpRequest");

            
            RequestConfig localRequestConfig = RequestConfig.copy(requestConfig).setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout).build();
            httpget.setConfig(localRequestConfig);

            CloseableHttpResponse response = httpClient.execute(httpget); 
            

            setCookie(response);
            
            
            try{
            	
            	
            	
            	if(response.getStatusLine().toString().indexOf("302 Found") > 0) {
             	   return response.getFirstHeader("Location").getValue();
                }
                HttpEntity entity = response.getEntity(); 
                
                String res = EntityUtils.toString(entity, "UTF-8");
                
                if(res != null && res.length() > 0 ){
                	//System.out.println(res);
                	
                	if(res.toLowerCase().contains("robot")) {
                		System.out.println(res);
                		updateStatusCode(-1);
                		return "";
                	}
                	
                	
                    if(!res.contains("{")) {
                    	
                    	System.out.println("grab matches without { failed");
                    	
                    	updateStatusCode(-3);
                    	
                    	return "";
                    }
                    
                    //System.out.println(res);
                    
                    parseDanshiMatches(res);
                	
                    return res;
                }
            }finally{
                httpget.releaseConnection();
                response.close();
            }
            

            

        }catch (Exception e){
        	e.printStackTrace();
        }
        
        return null;

    }
    
    
    
    public int Login() {
    	
    	WebDriver driver =new ChromeDriver(); 
    	
    	try {

            System.out.println(ACCOUNT+":before get:" + driver.manage().getCookies());
            
            driver.manage().window().maximize();
            
            
            driver.get(ADDRESS);

            
            
            System.out.println(ACCOUNT+"after enter main:" + driver.manage().getCookies());
    		
            
            boolean illeague = true;
            
    		
            try {
            	System.out.println(driver.findElement(By.id("login")));
            }catch(Exception e) 
            {
            	illeague = false;
            }
            
            
            if(illeague == false) {
            	Thread.sleep(2000);
            	driver.get(ADDRESS);
            }
            
           
            
            
            driver.findElement(By.name("loginId")).sendKeys(new  String[] {ACCOUNT});
            driver.findElement(By.name("password")).sendKeys(new  String[] {PWD}); 
            driver.findElement(By.id("login")).click();
            
            Thread.sleep(1000);
            
            driver.get(ADDRESS + "member-service/v1/account-balance?locale=zh_CN"); 
            
            Thread.sleep(2000);
            
            Set<Cookie> cookies = driver.manage().getCookies();
            
             
             for(Cookie cookie: cookies) {
            	 
            	 

             	myCookies.put(cookie.getName(), cookie.getValue());
             	
             	//System.out.println(cookie);

             }
             
             
             if(myCookies.size() < 2) {
            	 return -1;
             }

//    		
//    		HttpPost httppost = new HttpPost(ADDRESS + "member-service/v1/login?locale=zh_CN"); 
//
//    		String postcookies = getmyCookie(false);
//    		
//    		if(!postcookies.equals("")) {
//    			httppost.addHeader("Cookie", postcookies);
//    		}
//
//            
//            httppost.addHeader("Accept-Language","zh-CN,zh;q=0.8");
//            httppost.addHeader("Accept","*/*");
//            httppost.addHeader("Accept-Encoding","");
//            
//            httppost.addHeader("Connection","keep-alive");
//            httppost.addHeader("Cache-Control","max-age=0");
//            httppost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//            httppost.addHeader("Host", "www.ps3838.com");
//            httppost.addHeader("Referer", ADDRESS + "zh-cn/");
//            httppost.addHeader("X-Requested-With", "XMLHttpRequest");
//            httppost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");    
//            
//           
//            String loginstr = "loginId=" + ACCOUNT + "&password=" + PWD;
//            
//            StringEntity s = new StringEntity(loginstr);
//            
//            httppost.setEntity(s);
//            
//            RequestConfig localRequestConfig = RequestConfig.copy(requestConfig).setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout).build();
//            
//            httppost.setConfig(localRequestConfig);
//           
//            CloseableHttpResponse response = httpClient.execute(httppost);
//
//            setCookie(response);
//            
//            HttpEntity entity = response.getEntity(); 
//            
//            String res = EntityUtils.toString(entity);
//            
//            loginTime = System.currentTimeMillis();
            
            driver.quit();
            
            if(myCookies.containsKey("JSESSIONID")){
            	
            	Thread.sleep(2000);
            	
            	updateStatusCode(1);
            	
                return 1;
                
                
                
            }
    		
    		
    		return -1;
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    	
    	driver.quit();
    	
    	return -1;
    	
    }
    
    
    
    

    
    
    
    public String getBalance() {
    	
    	        try {  

    	            HttpGet httpget = new HttpGet(ADDRESS + "member-service/v2/account-balance?locale=zh_CN");
    	            
    	            
    	            

    	            String getcookies = getmyCookie(true);
    	            
    	            if(getcookies.equals("")) {
    	            	return null;
    	            }else {
    	            	httpget.addHeader("Cookie", getcookies);
    	            }
    	            
    	            httpget.addHeader("Accept","*/*");
    	            
    	            httpget.addHeader("Accept-Encoding","");
    	            httpget.addHeader("Accept-Language","en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7");
    	            httpget.addHeader("Connection","keep-alive");
    	            httpget.addHeader("Host","www.ps3838.com");

    	            httpget.addHeader("Referer",ADDRESS + "zh-cn/sports");
    	            
    	            httpget.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    	            httpget.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
    	            httpget.addHeader("X-Requested-With", "XMLHttpRequest");


    	            CloseableHttpResponse response = httpClient.execute(httpget); 
    	            

    	            
    	            
    	            
    	            try{

    	            	if(response.getStatusLine().toString().indexOf("302 Found") > 0) {
    	             	   return response.getFirstHeader("Location").getValue();
    	                }
    	                HttpEntity entity = response.getEntity(); 
    	                
    	                String res = EntityUtils.toString(entity, "UTF-8");
    	                
    	                if(res.contains("betCredit")) {  	
    	                	JSONObject details = new JSONObject(res);


    	                	double balance = details.getDouble("betCredit");
    	                	

    	                	
    	                	updateStatusCode(2);
    	                	Common.logOut("获取余额成功");
    	                	return Double.toString(balance);
    	                }else {
    	                	
    	                	if(res.contains("request timed out")) {
    	                		
    	                		System.out.println("request time out, no need to relogin");
    	                		
    	                	
    	                	}else {
    	                		
    	                		System.out.println("ps38 get balance failed:" + res);
    	                		
    	                		updateStatusCode(-1);
    	                	}
    	                	
    	                	
    	                	
    	                	
    	                	
    	                }
    	            }finally{
    	                httpget.releaseConnection();
    	                response.close();
    	            }
    	            

    	            

    	        }catch (Exception e){
    	        	e.printStackTrace();
    	        }
    	        
        		System.out.println("ps38 get balance failed exception:");
        		
        		updateStatusCode(-1);
    	        
    	        return null;
	}





    
    
    
    
    
	public  void setCookie(CloseableHttpResponse httpResponse)
	{
		
		
		Header headers[] = httpResponse.getHeaders("Set-Cookie");
		if (headers == null || headers.length==0)
		{
			
			return;
		}

		String cookie = "";
		for (int i = 0; i < headers.length; i++) {
			cookie = headers[i].getValue();
			
			
			
			String namevalue = cookie.split("; ")[0];
			String name = namevalue.split("=",2)[0];
			String value = namevalue.split("=", 2)[1];
			
			myCookies.put(name, value);
			
			
		}
		
		System.out.println("after response cookies:" + myCookies);

	}
    
    public String getmyCookie(boolean withJS) {
    	
    	String cookies = "";
    	
    	boolean first = true;
    	
    	for(String name: myCookies.keySet()) {
    		if(name.equals("JSESSIONID") && withJS == false) {
    			continue;
    		}
    		
    		if(first == false) {
    			cookies += ";";
    		}
    		
    		cookies += name + "=" + myCookies.get(name);
    		
    		first = false;
    		
    	}
    	
    	return cookies;

    	
    }
    
    private void parseMatches(String matchStr) {
    	
    	String resout = "";
    	
    	try {
    		
    		PS38Manager.danshiEventsLock.readLock().lock();
    		
    		PS38Manager.ps38Events.clear();
    		
    		
    		JSONObject sports = new JSONObject(matchStr);
    		
    		
    		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
    		
    		
    		
    		
    		//滚球盘
    		JSONArray rollGame = sports.getJSONArray("l");    		
    		JSONArray rollEvents = rollGame.getJSONArray(0);
    		rollEvents = rollEvents.getJSONArray(2);
    		
    		
    		
    		JSONArray oneLeague = null;
    		
    		for(int i = 0; i < rollEvents.length(); i++){
    			oneLeague = rollEvents.getJSONArray(i);
    			
    			String leagueName = oneLeague.getString(1);
    			
    			if(leagueName.contains("角球") || leagueName.contains("红黄牌") || leagueName.contains("晋级")) {
    				continue;
    			}
    			
    			JSONArray oneLeagueEvents = oneLeague.getJSONArray(2);
    			
    			
    			JSONArray oneEvent = null;
    			for(int j = 0; j < oneLeagueEvents.length(); j++) {
    				oneEvent = oneLeagueEvents.getJSONArray(j);
    				
    				long eventId = oneEvent.getLong(0);
    				String homeTeam = oneEvent.getString(1);
    				String awayTeam = oneEvent.getString(2);
    				long eventTime = oneEvent.getLong(4);
    				
    				
    				
    				
    				if(homeTeam.contains("角球") || homeTeam.contains("红黄牌") || homeTeam.contains("晋级")) {
        				continue;
        			}
    				
    				
    				
    				
    				JSONObject odds = oneEvent.getJSONObject(8);
    				
    				int homeTeamScore = 0;
    				int awayTeamScore = 0;
    				

    				try {
    					
        				homeTeamScore = oneEvent.getJSONArray(9).getInt(0);
        				awayTeamScore = oneEvent.getJSONArray(9).getInt(1);
    					
    					
    				}catch(Exception e) {
    					//e.printStackTrace();
    				}
    				
    				String duringTime = "";
    				
    				try {
    					duringTime = oneEvent.getString(16) + oneEvent.getString(15);
    				}catch(Exception e) {
    					
    				}
    				
    				
    				Event[] ps38event = {new Event(), new Event(), new Event(), new Event(), new Event()};
    				
    				
    				//Event ps38event = new Event();
    				
    				for(Event e: ps38event) {
        				e.eventId = eventId;
        				e.leagueName = leagueName;
        				e.homeTeam = homeTeam;
        				e.awayTeam = awayTeam;
        				e.eventTime = eventTime;
        				e.duringTime = duringTime;
        				e.homeTeamScore = homeTeamScore;
        				e.awayTeamScore = awayTeamScore;
    				}
    				

    				
    				boolean[] hasPankou = {false, false,false,false,false};
    				
//    				System.out.println(leagueName);
//    				
//    				System.out.println(eventId);
//    				System.out.println(homeTeam);
//    				System.out.println(awayTeam);
//    				System.out.println(df.format(eventTime));
//    				
//    				System.out.println(Integer.toString(homeTeamScore)+ ":" + Integer.toString(awayTeamScore));
//    				
//    				System.out.println(duringTime);
    				
    				
    				
    				
    				int len = odds.length();
    				
    				
    				if(len >=1 ) {
    					
    					if(!odds.has("0")) {
    						continue;
    					}
    					
    					
        				//全场
        				JSONArray whole = odds.getJSONArray("0");
        				
        				
        				
        				//全场让球盘盘口赔率
        				JSONArray wholeRQP = whole.getJSONArray(0);    	
        				
        				//System.out.println("wholeRQP:" + wholeRQP.toString());
        				
        				
        				
        				
        				for(int ii = 0; ii < wholeRQP.length(); ii++) {
        					
            				JSONArray wholeRQPDetail = wholeRQP.getJSONArray(ii);
            				
            				
            				//System.out.println("wholeRQPDetail:" + wholeRQPDetail.toString());
            				
//            				Double wholeRQPPankou = wholeRQPDetail.getDouble(2);
//            				Double wholeRQPPankouUp = wholeRQPDetail.getDouble(3);
//            				Double wholeRQPPankouDown = wholeRQPDetail.getDouble(4);
            				
            				Double wholeRQPPankou = wholeRQPDetail.getDouble(0);
            				String wholeRQPPankouUp = wholeRQPDetail.getString(3);
            				String wholeRQPPankouDown = wholeRQPDetail.getString(4);
            				
            				
            				String wholeRQPBetID = Long.toString(wholeRQPDetail.getLong(7));
            				
            				
            				
            				
            				
            				hasPankou[ii] = true;
            				ps38event[ii].wholerqppankou = Double.toString(wholeRQPPankou);
            				ps38event[ii].wholeRQPPankouUp = wholeRQPPankouUp;
            				ps38event[ii].wholeRQPPankouDown = wholeRQPPankouDown;
            				ps38event[ii].wholeRQPBetID = wholeRQPBetID;
            				
//            				System.out.println(wholeRQPPankou);
//            				System.out.println(wholeRQPPankouUp);
//            				System.out.println(wholeRQPPankouDown);
            				
        					
        				}
        				
        				

        				
        				
        				
        				//全场大小球盘盘口赔率
        				JSONArray wholeDXP = whole.getJSONArray(1);
        				
        				for(int ii = 0; ii < wholeDXP.length(); ii++) {
            				JSONArray wholeDXPDetail = wholeDXP.getJSONArray(ii);
            				
            				
            				
            				
            				Double wholeDXPPankou = wholeDXPDetail.getDouble(1);
            				Double wholeDXPPankouUp = 0.0;
            				try {
            					wholeDXPPankouUp = wholeDXPDetail.getDouble(2);
            				}catch(Exception e) {
            					//e.printStackTrace();
            					//wholeDXPPankouUp = Double.parseDouble(wholeDXPDetail.getString(2));
            				}
            				Double wholeDXPPankouDown = 0.0;
            				try {
            					wholeDXPPankouDown = wholeDXPDetail.getDouble(3);
            				}catch(Exception e) {
            					//e.printStackTrace();
            					//wholeDXPPankouDown = Double.parseDouble(wholeDXPDetail.getString(3));
            				}
            				
            				
            				String wholeDXPBetID = Long.toString(wholeDXPDetail.getLong(4));
            				
            				hasPankou[ii] = true;
            				ps38event[ii].wholeDXPPankou = Double.toString(wholeDXPPankou);
            				ps38event[ii].wholeDXPPankouUp = Double.toString(wholeDXPPankouUp);
            				ps38event[ii].wholeDXPPankouDown = Double.toString(wholeDXPPankouDown);
            				ps38event[ii].wholeDXPBetID = wholeDXPBetID;
            				


        				}
        				

        				
    				}
    				
    				//半场
    				if(len >=2 ) {
        				
    					try {
            				JSONArray half = odds.getJSONArray("1");

            				
            				//half rqp
            				JSONArray halfRQP = half.getJSONArray(0);
            				
            				if(halfRQP.length() >0) {
    	        				for(int ii = 0; ii < halfRQP.length(); ii++) {
    	        					
    	            				JSONArray halfRQPDetail = halfRQP.getJSONArray(ii);
    	            				Double halfRQPPankou = halfRQPDetail.getDouble(0);
    	            				String halfRQPPankouUp = halfRQPDetail.getString(3);
    	            				String halfRQPPankouDown = halfRQPDetail.getString(4);
    	            				
    	            				String halfRQPBetID = Long.toString(halfRQPDetail.getLong(7));
    	            				
    	            				hasPankou[ii] = true;
    	            				ps38event[ii].halfrqppankou = Double.toString(halfRQPPankou);
    	            				ps38event[ii].halfRQPPankouUp = halfRQPPankouUp;
    	            				ps38event[ii].halfRQPPankouDown = halfRQPPankouDown;
    	            				ps38event[ii].halfRQPBetID = halfRQPBetID;
    	
    	        					
    	        				}
            				
            				
            				}
            				
            				//半场大小球盘盘口赔率
            				JSONArray halfDXP = half.getJSONArray(1);
            				if(halfDXP.length()>1) {
                				for(int ii = 0; ii< halfDXP.length(); ii++) {
                    				JSONArray halfDXPDetail = halfDXP.getJSONArray(ii);
                    				
                    				Double halfDXPPankou = halfDXPDetail.getDouble(1);
                    				Double halfDXPPankouUp = halfDXPDetail.getDouble(2);
                    				Double halfDXPPankouDown = halfDXPDetail.getDouble(3);
                    				String halfDXPBetID = Long.toString(halfDXPDetail.getLong(4));
                    				
                    				
                    				hasPankou[ii] = true;
                    				ps38event[ii].halfDXPPankou = Double.toString(halfDXPPankou);
                    				ps38event[ii].halfDXPPankouUp = Double.toString(halfDXPPankouUp);
                    				ps38event[ii].halfDXPPankouDown = Double.toString(halfDXPPankouDown);
                    				ps38event[ii].halfBetID = halfDXPBetID;

                				}
            				}else if(halfDXP.length()==1) {
                				for(int ii = 0; ii< halfDXP.length(); ii++) {
                    				JSONArray halfDXPDetail = halfDXP.getJSONArray(ii);
                    				boolean hasException = false;
                    				try {
                        				Double halfDXPPankou = halfDXPDetail.getDouble(1);
                        				Double halfDXPPankouUp = halfDXPDetail.getDouble(2);
                        				Double halfDXPPankouDown = halfDXPDetail.getDouble(3);
                        				String halfDXPBetID = Long.toString(halfDXPDetail.getLong(4));
                        				
                        				
                        				hasPankou[ii+1] = true;
                        				ps38event[ii+1].halfDXPPankou = Double.toString(halfDXPPankou);
                        				ps38event[ii+1].halfDXPPankouUp = Double.toString(halfDXPPankouUp);
                        				ps38event[ii+1].halfDXPPankouDown = Double.toString(halfDXPPankouDown);
                        				ps38event[ii+1].halfBetID = halfDXPBetID;
                    				}catch(Exception e) {
                    					hasException = true;
                    				}

                    				if(hasException==true) {
                    					
                    				}
                				}
            				}
    					}catch(Exception e) {
    						
    					}
        				



    				}


    				
    				for(int ii = 0; ii < hasPankou.length; ii++) {
    					if(hasPankou[ii] == true) {
    						PS38Manager.ps38Events.add(ps38event[ii]);        					
        				}
    				}
    				

    			}
    			
    		}
    		
    		for(int i = 0; i < PS38Manager.ps38DanshiEvents.size(); i++) {
    			PS38Manager.ps38Events.add(PS38Manager.ps38DanshiEvents.elementAt(i));
    		}
    		

    		updateStatusCode(3);
    		
    		
    		DaShui.mainWnd.updatePS38EventsTable(PS38Manager.ps38Events);
    		
    		DaShui.mainWnd.updateTeamMatchPS38Teams(PS38Manager.ps38Events);
    		
    		DaShui.isnps38EventManager.updateps38events(PS38Manager.ps38Events);
    		
    		PS38Manager.danshiEventsLock.readLock().unlock();
    		
    		
    	}catch(Exception e) {
    		
    		PS38Manager.danshiEventsLock.readLock().unlock();
    		e.printStackTrace();
    		
    		System.out.println("parsed failed grab failed:" + resout);
    		
    		updateStatusCode(-3);
    	}
    	
    	
    }
    
    private void parseDanshiMatches(String matchStr) {
    	
    	String resout = "";
    	
    	try {
    		
    		PS38Manager.danshiEventsLock.writeLock().lock();
    		
    		PS38Manager.ps38DanshiEvents.clear();
    		
    		PS38Manager.ps38Events.clear();
    		
    		JSONObject sports = new JSONObject(matchStr);
    		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");    		
    		JSONArray oneLeague = null;    		
    		//单式盘
    		JSONArray danshiGame = sports.getJSONArray("n");
    		JSONArray danshiEvents = danshiGame.getJSONArray(0);
    		danshiEvents = danshiEvents.getJSONArray(2);
    		
    		for(int i = 0; i < danshiEvents.length(); i++){
    			oneLeague = danshiEvents.getJSONArray(i);
    			
    			String leagueName = oneLeague.getString(1);
    			
    			if(leagueName.contains("角球") || leagueName.contains("红黄牌") || leagueName.contains("晋级")) {
    				continue;
    			}
    			
    			JSONArray oneLeagueEvents = oneLeague.getJSONArray(2);
    			
    			
    			JSONArray oneEvent = null;
    			for(int j = 0; j < oneLeagueEvents.length(); j++) {
    				oneEvent = oneLeagueEvents.getJSONArray(j);
    				
    				
    				
    				long eventId = oneEvent.getLong(0);
    				String homeTeam = oneEvent.getString(1);
    				String awayTeam = oneEvent.getString(2);
    				long eventTime = oneEvent.getLong(4);
    				
    				JSONObject odds = oneEvent.getJSONObject(8);
    				
    				if(homeTeam.contains("角球") || homeTeam.contains("红黄牌") || homeTeam.contains("晋级")) {
        				continue;
        			}
    				
    				
    				int homeTeamScore = 0;
    				int awayTeamScore = 0;
    				

    				try {
    					
        				homeTeamScore = oneEvent.getJSONArray(9).getInt(0);
        				awayTeamScore = oneEvent.getJSONArray(9).getInt(1);
    					
    					
    				}catch(Exception e) {
    					//e.printStackTrace();
    				}
    				
    				String duringTime = "";
    				
    				try {
    					duringTime = oneEvent.getString(16) + oneEvent.getString(15);
    				}catch(Exception e) {
    					
    				}
    				
    				
    				
    				Event[] ps38event = {new Event(), new Event(), new Event(), new Event(), new Event()};
    				
    				
    				//Event ps38event = new Event();
    				
    				for(Event e: ps38event) {
        				e.eventId = eventId;
        				e.leagueName = leagueName;
        				e.homeTeam = homeTeam;
        				e.awayTeam = awayTeam;
        				e.eventTime = eventTime;
        				e.duringTime = duringTime;
        				e.homeTeamScore = homeTeamScore;
        				e.awayTeamScore = awayTeamScore;
    				}
    				

    				
    				boolean[] hasPankou = {false, false,false, false,false};
    				
//    				System.out.println(leagueName);
//    				
//    				System.out.println(eventId);
//    				System.out.println(homeTeam);
//    				System.out.println(awayTeam);
//    				System.out.println(df.format(eventTime));
//    				
//    				System.out.println(Integer.toString(homeTeamScore)+ ":" + Integer.toString(awayTeamScore));
//    				
//    				System.out.println(duringTime);
    				
    				
    				
    				
    				int len = odds.length();
    				
    				
    				if(len >=1 ) {
        				//全场
    					
    					//System.out.println("odds~~~~~~~~~~~" + odds.toString());
    					
    					resout = odds.toString();
    					
    					if(!odds.has("0")) {
    						continue;
    					}
    					
    					
        				JSONArray whole = odds.getJSONArray("0");
        				
        				
        				
        				//全场让球盘盘口赔率
        				JSONArray wholeRQP = whole.getJSONArray(0);    	
        				
        				//System.out.println("wholeRQP:" + wholeRQP.toString());
        				
        				
        				
        				
        				if(wholeRQP.length() >0) {
	        				for(int ii = 0; ii < wholeRQP.length(); ii++) {
	        					
	            				JSONArray wholeRQPDetail = wholeRQP.getJSONArray(ii);
	            				Double wholeRQPPankou = wholeRQPDetail.getDouble(0);
	            				String wholeRQPPankouUp = wholeRQPDetail.getString(3);
	            				String wholeRQPPankouDown = wholeRQPDetail.getString(4);
	            				
	            				String wholeRQPBetID = Long.toString(wholeRQPDetail.getLong(7));
	            				
	            				hasPankou[ii] = true;
	            				ps38event[ii].wholerqppankou = Double.toString(wholeRQPPankou);
	            				ps38event[ii].wholeRQPPankouUp = wholeRQPPankouUp;
	            				ps38event[ii].wholeRQPPankouDown = wholeRQPPankouDown;
	            				ps38event[ii].wholeRQPBetID = wholeRQPBetID;
	
	        					
	        				}
        				
        				
        				}
        				
        				
        				
        				//全场大小球盘盘口赔率
        				JSONArray wholeDXP = whole.getJSONArray(1);

        				for(int ii = 0; ii< wholeDXP.length(); ii++) {
            				JSONArray wholeDXPDetail = wholeDXP.getJSONArray(ii);
            				
            				Double wholeDXPPankou = wholeDXPDetail.getDouble(1);
            				Double wholeDXPPankouUp = wholeDXPDetail.getDouble(2);
            				Double wholeDXPPankouDown = wholeDXPDetail.getDouble(3);
            				String wholeDXPBetID = Long.toString(wholeDXPDetail.getLong(4));
            				
            				
            				hasPankou[ii] = true;
            				ps38event[ii].wholeDXPPankou = Double.toString(wholeDXPPankou);
            				ps38event[ii].wholeDXPPankouUp = Double.toString(wholeDXPPankouUp);
            				ps38event[ii].wholeDXPPankouDown = Double.toString(wholeDXPPankouDown);
            				ps38event[ii].wholeDXPBetID = wholeDXPBetID;

        				}
        				
    				}
    				
    				//半场
    				if(len >=2 ) {
        				
        				
    					try {
            				JSONArray half = odds.getJSONArray("1");

            				
            				//half rqp
            				JSONArray halfRQP = half.getJSONArray(0);
            				
            				if(halfRQP.length() >0) {
    	        				for(int ii = 0; ii < halfRQP.length(); ii++) {
    	        					
    	            				JSONArray halfRQPDetail = halfRQP.getJSONArray(ii);
    	            				Double halfRQPPankou = halfRQPDetail.getDouble(0);
    	            				String halfRQPPankouUp = halfRQPDetail.getString(3);
    	            				String halfRQPPankouDown = halfRQPDetail.getString(4);
    	            				
    	            				String halfRQPBetID = Long.toString(halfRQPDetail.getLong(7));
    	            				
    	            				hasPankou[ii] = true;
    	            				ps38event[ii].halfrqppankou = Double.toString(halfRQPPankou);
    	            				ps38event[ii].halfRQPPankouUp = halfRQPPankouUp;
    	            				ps38event[ii].halfRQPPankouDown = halfRQPPankouDown;
    	            				ps38event[ii].halfRQPBetID = halfRQPBetID;
    	
    	        					
    	        				}
            				
            				
            				}
            				
            				
            				//半场大小球盘盘口赔率
            				JSONArray halfDXP = half.getJSONArray(1);
            				if(halfDXP.length()>1) {
                				for(int ii = 0; ii< halfDXP.length(); ii++) {
                    				JSONArray halfDXPDetail = halfDXP.getJSONArray(ii);
                    				
                    				Double halfDXPPankou = halfDXPDetail.getDouble(1);
                    				Double halfDXPPankouUp = halfDXPDetail.getDouble(2);
                    				Double halfDXPPankouDown = halfDXPDetail.getDouble(3);
                    				String halfDXPBetID = Long.toString(halfDXPDetail.getLong(4));
                    				
                    				
                    				hasPankou[ii] = true;
                    				ps38event[ii].halfDXPPankou = Double.toString(halfDXPPankou);
                    				ps38event[ii].halfDXPPankouUp = Double.toString(halfDXPPankouUp);
                    				ps38event[ii].halfDXPPankouDown = Double.toString(halfDXPPankouDown);
                    				ps38event[ii].halfBetID = halfDXPBetID;

                				}
            				}else if(halfDXP.length()==1) {
                				for(int ii = 0; ii< halfDXP.length(); ii++) {
                    				JSONArray halfDXPDetail = halfDXP.getJSONArray(ii);
                    				boolean hasException = false;
                    				try {
                        				Double halfDXPPankou = halfDXPDetail.getDouble(1);
                        				Double halfDXPPankouUp = halfDXPDetail.getDouble(2);
                        				Double halfDXPPankouDown = halfDXPDetail.getDouble(3);
                        				String halfDXPBetID = Long.toString(halfDXPDetail.getLong(4));
                        				
                        				
                        				hasPankou[ii+1] = true;
                        				ps38event[ii+1].halfDXPPankou = Double.toString(halfDXPPankou);
                        				ps38event[ii+1].halfDXPPankouUp = Double.toString(halfDXPPankouUp);
                        				ps38event[ii+1].halfDXPPankouDown = Double.toString(halfDXPPankouDown);
                        				ps38event[ii+1].halfBetID = halfDXPBetID;
                    				}catch(Exception e) {
                    					hasException = true;
                    				}

                    				if(hasException==true) {
                    					
                    				}
                				}
            				}
    					}catch(Exception e) {
    						
    					}


    				}
    				
    				for(int ii = 0; ii < hasPankou.length; ii++) {
    					if(hasPankou[ii] == true) {    						
    						PS38Manager.ps38DanshiEvents.add(ps38event[ii]);    						
        				}
    				}
    			}
    			
    		}
    		
    		
    		for(int i = 0; i < PS38Manager.ps38DanshiEvents.size(); i++) {
    			PS38Manager.ps38Events.add(PS38Manager.ps38DanshiEvents.elementAt(i));
    		}
    		

    		
    		
    		//DaShui.mainWnd.updatePS38EventsTable(PS38Manager.ps38Events);
    		
    		//DaShui.mainWnd.updateTeamMatchPS38Teams(PS38Manager.ps38Events);
    		
    		//DaShui.isnps38EventManager.updateps38events(PS38Manager.ps38Events);
    		
    		updateStatusCode(3);
    		PS38Manager.danshiEventsLock.writeLock().unlock();
    		
    		
    	}catch(Exception e) {
    		
    		PS38Manager.danshiEventsLock.writeLock().unlock();
    		e.printStackTrace();
    		
    		System.out.println("parsed failed grab failed:" + resout);
    		
    		updateStatusCode(-3);
    	}
    	
    	
    }
    
}
